# -*- coding: utf-8 -*-
# @Time        :2025/4/7 17:28
# @Author      :文刀水寿
# @File        : views.py
"""
 @Description :路由 +  视图函数
"""
# 蓝图
from flask import Blueprint, request, render_template, g, session, current_app
from .models import *
from .exts import cache
import time

blue = Blueprint('user', __name__)


# 使用缓存
@blue.route('/')
@cache.cached(timeout=20)  # 给视图函数加一个缓存 20 秒
def index():
    print('Index')

    time.sleep(5)
    return 'index2'

# AOP切面编程
# 钩子函数
# 中间件
# before_request: 每一次请求之前访问
@blue.before_request
def before():
    print('before_request')

    # request
    # print(request.path)
    # print(request.method)
    # print(request.remote_addr)  # 客户端ip地址

    # 简单的反爬
    # print(request.user_agent)  # python-requests/2.32.3
    # if "python" in request.user_agent.string:
    #     return "您正在使用python爬虫，再见！！"

    # 针对IP做反爬
    ip = request.remote_addr

    # cache.get()
    # cache.set()

    if cache.get(ip):
        # 做了拦截， 不会进入视图函数
        return "小伙子别爬了！"
    else:
    # 对每个ip设置缓存，1秒内不让重复访问
        cache.set(ip, 'value', timeout=1)


    # Flask内置对象
    # request ：请求对象
    # session：会话对象
    # g： global全局对象
    # current_app: Flask应用对象
    g.star = '杰伦'
    print(g.star)
    print(current_app)  # <Flask 'APP'>
    print(current_app.config)  # <Config {'DEBUG': True, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'SECRET_KEY': None, 'SECRET_KEY_FALLBACKS': None, 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(days=31), 'USE_X_SENDFILE': False, 'TRUSTED_HOSTS': None, 'SERVER_NAME': None, 'APPLICATION_ROOT': '/', 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_COOKIE_PARTITIONED': False, 'SESSION_COOKIE_SAMESITE': None, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'MAX_FORM_MEMORY_SIZE': 500000, 'MAX_FORM_PARTS': 1000, 'SEND_FILE_MAX_AGE_DEFAULT': None, 'TRAP_BAD_REQUEST_ERRORS': None, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'TEMPLATES_AUTO_RELOAD': None, 'MAX_COOKIE_SIZE': 4093, 'PROVIDE_AUTOMATIC_OPTIONS': True, 'SQLALCHEMY_DATABASE_URI': 'sqlite:///sqlite3.db', 'SQLALCHEMY_TRACK_MODIFICATIONS': False, 'SQLALCHEMY_ENGINE_OPTIONS': {}, 'SQLALCHEMY_ECHO': False, 'SQLALCHEMY_BINDS': {}, 'SQLALCHEMY_RECORD_QUERIES': False}>

